package com.imgpro.handler;

import com.imgpro.Constant.MessageConstant;
import com.imgpro.Exception.BaseException;
import com.imgpro.Exception.DeletionNotAllowedException;
import com.imgpro.Exception.SignUpFailedException;
import com.imgpro.Exception.UpdateFailedException;
import com.imgpro.Result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.security.auth.login.AccountNotFoundException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
//        Duplicate entry '台熙瑶' for key 'employee.idx_username'
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split(" ");
            String username = split[2].substring(1, split[2].lastIndexOf("'"));
            log.error("出现重复插入值异常：{}", ex.getMessage());
            return Result.error("服务器异常——" + username + MessageConstant.DUPLICATE_ENTRY);
        }
        return Result.error("服务器异常" + MessageConstant.UNKNOWN_ERROR);
    }

    @ExceptionHandler
    public Result exceptionHandler(DeletionNotAllowedException ex){
        String message = ex.getMessage();
        log.info("不允许删掉,{}",message );
        return Result.error(message);
    }

    @ExceptionHandler
    public Result exceptionHandler(SignUpFailedException ex){
        String message = ex.getMessage();
        log.info("用户注册信息已经存在,{}",message );
        return Result.error(message);
    }

    @ExceptionHandler
    public Result exceptionHandler(AccountNotFoundException ex){
        String message = ex.getMessage();
        log.info("账号不存在我去,{}",message );
        return Result.error(message);
    }

    @ExceptionHandler
    public Result exceptionHandler(UpdateFailedException ex){
        String message = ex.getMessage();
        log.info("修改用户出现问题,{}",message );
        return Result.error(message);
    }
}
